#!/usr/bin/python
import logging
import modules.parser
import modules.Warehouse
from google.appengine.api import mail

####################for test ###############
dicts = {
        'aqi': ['http://www.aqicn.info/city/all',
            { 
                'PageUpdateTime': [ r'<i>This page has been generated ([^<]+)',  'val != ref', '', '' ],
                'Haidian Wanliu': [ r'<span>Haidian Wanliu\W+\D+(\d+)',  'val != ref', '', '' ], 
                'Beijing': [ r'<span>Beijing\W+\D+(\d+)',  'val != ref', '', '' ], 
                'Changzhou': [ r'<span>Changzhou\W+\D+(\d+)',  'val != ref', '', '' ], 
                'Tangshan': [ r'<span>Tangshan\W+\D+(\d+)',  'val != ref', '', '' ]
                }
            ],
        'exchange rate': ['http://www.x-rates.com/calculator/?from=JPY&to=CNY&amount=100',
            { 
                'PageUpdateTime': [ r'CNY</span>(?:\S+\s+){2}<span[^>]+>(.+)</span>', '1!=1', '', '' ], 
                '<Japanese Yan to Chinese Yuan> 100Yan': [ r'100.00 JPY\D+(\d+.\d*)\D+(\d+)', 'abs(float(val)-float(ref))>float(p1)', '0.1', '' ] 
                }
            ]
        }

mailsender='acqu-center <acqu.center@gmail.com>'
mailrecv=['acqu-center@googlegroups.com']
mailtitle='A notification from acqu-center.'

############################################

def main():
    gate = modules.Warehouse.Warehouse("15mins")
    report = ""

    for label in dicts.keys():
        box = gate.CHECKOUT(label)

####################for test ###############
        if box is None:
            box = modules.Warehouse.box(dicts[label]) 
        else:
            box.update(dicts[label])
###########################################

        p=modules.parser.parser(box)
        p.run()
        if p.isDirty():
            report+="\n------------>>>> "+label+" <<<<------------\n"+p.report()
        gate.CHECKIN(label, box)
    
    if report != "":
        logging.info(report)
        mail.send_mail(mailsender, mailrecv, mailtitle,report)

if __name__== '__main__':
    main()
